<?php

class TranslateController extends St_Controller_Action_Admin {

    public function indexAction() {
        if (!$this->acl->isAllow("view_translate")) {
            $this->_redirect("access/deny");
        }
        $m = str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
        $dir = $_SERVER["DOCUMENT_ROOT"] . str_replace("admin", "", $m) . "/languages/";

        $dh = opendir($dir);
        $filearr = array();

        while (($file = readdir($dh)) !== false) {
            if (strpos($file, ".")) {
                $filearr[$file] = $file;
            }
        }
        closedir($dh);
        
        $this->view->filearr = $filearr;
        
    }

    public function editAction() {
        if (!$this->acl->isAllow("edit_translate")) {
            $this->_forward("deny", "access");
            return;
        }

        $canAdd = true;
        $result = false;
        $uid = $this->_getParam("uid", false);
        $this->view->langfile = $uid;
        if (!$uid) {
            $this->_redirect("user");
        }
        $m = str_replace(basename($_SERVER['SCRIPT_NAME']), "", $_SERVER['SCRIPT_NAME']);
        $filecontent = include($_SERVER["DOCUMENT_ROOT"] . str_replace("admin", "", $m) . "/languages/" . $uid);
        $data = $this->_getParam("data", false);
        //var_dump($_POST);
        //die;
        if ($data) {
            //var_dump($data);
            //die;
            $result = array_merge((array) $filecontent, (array) $data);
            /* echo "<br><br>";
              var_dump($result);
              die; */

            $re = "<?php \n return " . var_export($result, 1) . "; \n ?>";
            $fp = fopen($_SERVER["DOCUMENT_ROOT"] . str_replace("admin", "", $m) . "/languages/" . $uid, 'w');
            fwrite($fp, $re);
            fclose($fp);
            $langname = ($uid == 'en.php') ? "English" : "Norway";
            $user = $this->_getCurrentUser();
            $this->logger->log($user['UserName'] . " edits " . $langname . " language file");
            if ($result) {

                $this->view->msg = "Update language successfully";
            } else {
                $this->view->msg = "Can't update language";
            }
        }
        $filecontent2 = include($_SERVER["DOCUMENT_ROOT"] . str_replace("admin", "", $m) . "/languages/" . $uid);
        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->baseUrl = $baseUrl;
        $this->view->searchUrl = $baseUrl . "admin/translate/edit/uid/" . $uid;
        if (isset($_POST['keyword'])) {
            if ($_POST['keyword'] != '') {
                $rowstemp = array();
                foreach ($filecontent as $key => $value) {
                    //echo $key;
                    if (strpos(strtolower($key), strtolower($_POST['keyword'])) !== false) {
                        $rowstemp[$key] = $value;
                        //echo $key;
                    } else {
                        //$valuestemp = array($value);
                        //$rowstemp[$key] = $valuestemp;
                        //echo $key."<br>";
                    }
                }
                $this->view->keyword = $_POST['keyword'];
                $filecontent2 = $rowstemp;
            }
        }

        Zend_Loader::loadClass("St_Lgd_Pagination");
        $pagination = new St_Lgd_Pagination ();
        $languageItems = '';
        $pageNumbers = '';
        if (count($filecontent2)) {
            $this->view->totalitem = count($filecontent2);
            if (isset($_POST['keyword'])) {
                if ($_POST['keyword'] != '') {
                    $pagenum = 1000;
                } else {
                    $pagenum = 10;
                }
            } else {
                $pagenum = 10;
            }
            $languageItems = $pagination->generate($filecontent2, $pagenum);
            // If we have items 
            if (count($languageItems) != 0) {
                // Create the page numbers
                $pageNumbers = $pagination->links();
                // Loop through all the items in the array
                /* foreach ($languageItems as $items) 
                  {
                  // Show the information about the item
                  echo '<p>aa</p>';
                  } */
                // print out the page numbers beneath the results
                //echo $pageNumbers;
            }
        }
        $this->view->filecontent = $languageItems;
        $this->view->pagination = $pageNumbers;
    }

    public function globalsettingAction() {

        $canAdd = true;
        $result = false;

        $this->view->baselink = St_Registry::getConfig("base_url");
        $typeObj = St_Registry::getDB();
        $datas = $typeObj->query("SELECT keyword, value  from setting where keyword='default_country'");
        $this->view->setting = $datas->fetchColumn(1);
        $datas = $typeObj->query("SELECT keyword, value  from setting where keyword='default_table_row_page'");
        $this->view->table_row = $datas->fetchColumn(1);
        $datas = $typeObj->query("SELECT keyword, value  from setting where keyword='default_session_row_page'");
        $this->view->session_row = $datas->fetchColumn(1);
        $countryObj = St_Registry::getDB();
        $datas = $countryObj->fetchAll("SELECT *  from st_countries");
        $this->view->countrylist = $datas;
        $data = $this->_getParam("data", false);

        if ($data) {

            if ($canAdd) {

                $typeObj = St_Registry::getDB();
                $result = $typeObj->query("update setting set value='" . $data['value'] . "' where keyword='default_country'");
                $result = $typeObj->query("update setting set value='" . $data['default_table_row_page'] . "' where keyword='default_table_row_page'");
                $result = $typeObj->query("update setting set value='" . $data['default_session_row_page'] . "' where keyword='default_session_row_page'");
                //$result = $siteObj->update($data, "keyword='default_country'");
            }

            if ($result) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['UserName'] . " edits the default country in Global Setting");
                $this->view->msg = "Update global setting successfully";
            } else {
                $this->view->msg = "Can't update global setting";
            }
            $this->view->data = $data;
            $this->_redirect("{$currentControllerName}/translate/globalsetting");
        }
    }

    public function locationAction() {

        $sorting = $this->_getParam("sorting", false);
        $type = $this->_getParam("type", false);
        if ($sorting == '') {
            $type = ' DESC';
            $sortby = "CourseLocationID" . $type;
        } else {
            switch ($sorting) {
                case 'name':
                    $sortby = "CourseLocationName" . $type;
                    break;
                case 'school':
                    $sortby = "SchoolID" . $type;
                    break;
                default:
                    $sortby = "CourseLocationID" . $type;
            }
        }

        Zend_Loader::loadClass("Zend_Paginator_Adapter_DbSelect");
        Zend_Loader::loadClass("Zend_Paginator");
        $db = St_Registry::getDB();
        if ($_SESSION['userSchool'] != '') {
            $select = $db->select()
                    ->from(array('u' => 'courselocations'))
                    ->where("SchoolID=" . $_SESSION['userSchool'])
                    ->order($sortby)
            ;
        } else {
            $select = $db->select()
                    ->from(array('u' => 'courselocations'))
                    ->order($sortby)
            ;
        }

        $adapter = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam("page", 1));
        $db = St_Registry::getDB();
        $perpage = $db->query("SELECT keyword, value  from setting where keyword='default_table_row_page'");
        $perpage = $perpage->fetchColumn(1);
        $paginator->setItemCountPerPage($perpage);
        $paginator->setPageRange(5);
        $type = $type == ' DESC' ? ' ASC' : ' DESC';
        $schoolObj = St_Registry::getDB();
        $datas = $schoolObj->fetchAll("SELECT * from school_list");
        ;
        $this->view->schoolObj = $datas;
        $this->view->baselink = St_Registry::getConfig("base_url");
        $this->view->typesorting = $type;
        $this->view->paginator = $paginator;
        $this->view->currentPage = $this->_getParam("page", 1);
        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->baseUrl = $baseUrl;
    }

    public function addlocationAction() {
        $db = St_Registry::getDB();
        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/externals/js/ajaxupload.js');
        $this->view->headLink()
                ->appendStylesheet($baseUrl . 'application/admin/externals/css/prettyPhoto.css');
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/externals/js/jquery.prettyPhoto.js');
        
        $currentControllerName = St_Registry::getControllerName();
        $canAdd = true;
        $result = false;
        $data = $this->_getParam("data", false);

        $schoolObj = St_Registry::getDB();
        $datas = $schoolObj->fetchAll("SELECT * from school_list");
        ;
        $this->view->schoolObj = $datas;
        $images = $this->_getParam("image", false);
        if ($data) {
            Zend_Loader::loadClass("St_Semester");
            $schoolObj = new St_Semester ();

            if ($data['CourseLocationName'] == "") {
                $canAdd = false;
            }
            if ($canAdd) {
                Zend_Loader::loadClass("St_CourseLocation");
                $courseLocationObj = new St_CourseLocation();
                $courseLocationObj->insert($data);                
                $courseLocationID = $db->lastInsertId();
                
                if (count($images) >= 1) {

                    $courseLocationImageObj = new St_CourseLocation(array('name' => 'courselocationimage'));
                    foreach ($images as $image) {
                        $img_data['Path'] = $image;
                        $img_data['courseLocationID'] = $courseLocationID;
                        $courseLocationImageObj->insert($img_data);
                    }
                }
            }

            if ($result && $canAdd) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['UserName'] . " adds a new Location:" . $data['CourseLocationName']);
                $this->view->msg = "Add new location successfully";
            } else {
                $this->view->msg = "Can't add location";
            }
            $this->_redirect("{$currentControllerName}/location");
        }
    }

    public function editlocationAction() {
        if (!$this->acl->isAllow("edit_semester")) {
            $this->_forward("deny", "access");
            return;
        }
        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/externals/js/ajaxupload.js');
        $this->view->headLink()
                ->appendStylesheet($baseUrl . 'application/admin/externals/css/prettyPhoto.css');
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/externals/js/jquery.prettyPhoto.js');
        
        $currentControllerName = St_Registry::getControllerName();
        $canAdd = true;
        $result = false;
        $uid = $this->_getParam("uid", false);
        if (!$uid) {
            $this->_redirect("user");
        }
        $schoolObj = St_Registry::getDB();
        $datas = $schoolObj->fetchAll("SELECT * from school_list");
        ;
        $this->view->schoolObj = $datas;

        $this->view->dataId = $uid;

        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'courselocations'))
                ->where("CourseLocationID  = '$uid'");
        $arrayRow = $db->fetchRow($select);

        if ($arrayRow) {
            $this->view->data = $arrayRow;
        }
        $img_url = $this->externalUrl . 'images/';
        $this->view->img_url = $img_url;
        // Binh add: 3-11-2011
        $select = $db->select()
                ->from(array('u' => 'courselocationimage'))
                ->where("CourseLocationID = '$uid'");
        $images = $db->fetchAll($select);
        $this->view->images = $images;
        
        $data = $this->_getParam("data", false);
        $images = $this->_getParam("image", false);
        if ($data) {

            if ($data['CourseLocationName'] == "") {
                $canAdd = false;
            }


            if ($canAdd) {
                Zend_Loader::loadClass("St_CourseLocation");
                $courseLocationObj = new St_CourseLocation();
                $courseLocationObj->update($data, "CourseLocationID = '$uid'");
                
                if (count($images) >= 1) {

                    $courseLocationImageObj = new St_CourseLocation(array('name' => 'courselocationimage'));
                    foreach ($images as $image) {
                        $img_data['Path'] = $image;
                        $img_data['courseLocationID'] = $uid;
                        $courseLocationImageObj->insert($img_data);
                    }
                }
            }

            if ($result) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['UserName'] . " edits CourseLocationID =" . $uid);
                $this->view->msg = "Update location successfully";
            } else {
                $this->view->msg = "Can't update location";
            }
            $this->view->data = $data;
            $this->_redirect("{$currentControllerName}/location");
        }
    }

    public function deletelocationAction() {


        $uid = $this->_getParam("uid", false);

        $currentControllerName = St_Registry::getControllerName();
        $typeObj = St_Registry::getDB();
        $result = $typeObj->query("DELETE FROM courselocations WHERE CourseLocationID =" . $uid);

        //redirect to other action
        $user = $this->_getCurrentUser();
        $this->logger->log($user['UserName'] . " deletes CourseLocationID =" . $uid);
        $this->_redirect("{$currentControllerName}/location");
    }

    public function transactionlogAction() {
        if (!$this->acl->isAllow("view_transactionlog")) {
            $this->_redirect("access/deny");
        }
        $sorting = $this->_getParam("sorting", false);
        $type = $this->_getParam("type", false);
        if ($sorting == '') {
            $type = ' DESC';
            $sortby = "DateTime" . $type;
        } else {
            switch ($sorting) {
                case 'ip':
                    $sortby = "IPAddress" . $type;
                    break;
                case 'txt':
                    $sortby = "TransactionText" . $type;
                    break;
                default:
                    $sortby = "DateTime" . $type;
            }
        }

        Zend_Loader::loadClass("Zend_Paginator_Adapter_DbSelect");
        Zend_Loader::loadClass("Zend_Paginator");
        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'transaction_log'))
                ->order($sortby)
        ;
        $adapter = new Zend_Paginator_Adapter_DbSelect($select);
        $paginator = new Zend_Paginator($adapter);
        $paginator->setCurrentPageNumber($this->_getParam("page", 1));
        
        $db = St_Registry::getDB();
        $config = St_Registry::getConfig('display');                
        $paginator->setItemCountPerPage ( $config['numberPerPage'] );                
        $paginator->setPageRange ( $config['pageRange'] );
        
        $type = $type == ' DESC' ? ' ASC' : ' DESC';
        $this->view->baselink = St_Registry::getConfig("base_url");
        $this->view->typesorting = $type;
        $this->view->paginator = $paginator;
        $this->view->currentPage = $this->_getParam("page", 1);
    }

    public function emailsettingAction() {
        $baseUrl = St_Registry::getConfig("base_url");
        $this->view->headLink()
                ->appendStylesheet($baseUrl . 'application/admin/externals/css/prettyPhoto.css');
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/externals/js/jquery.prettyPhoto.js');
        $this->view->headScript()
                ->appendFile($baseUrl . 'application/admin/externals/js/jquery.simpletip-1.3.1.pack.js');
        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'email_setting'))
                ->where("id  = 1");
        $arrayRow = $db->fetchRow($select);
        $this->view->option = $arrayRow;
        if ($_POST) {
            extract($_POST['data']);

            $smtp_config['smtpHost'] = $smtpHost;
            $smtp_config['smtpPort'] = $smtpPort;
            $smtp_config['smtpSsl'] = $smtpSsl;
            $smtp_config['smtpAuthentication'] = $smtpAuthentication;
            $smtp_config['smtpUsername'] = $smtpUsername;
            $smtp_config['smtpPassword'] = $smtpPassword;
            $options = json_encode($smtp_config);
            //var_dump($options);
            //die;
            $db = St_Registry::getDB();
            $db->query("update email_setting set smtp_options='" . $options . "' where id=1");
            $this->_redirect("{$currentControllerName}/translate/emailsetting");
        }
    }

    public function loadtestformAction() {
        
    }

    public function sendtestmailAction() {
        $baseUrl = St_Registry::getConfig("base_url");
        require_once($_SERVER["DOCUMENT_ROOT"] . $baseUrl . "library/phpmailer/class.phpmailer.php");
        require_once($_SERVER["DOCUMENT_ROOT"] . $baseUrl . "library/phpmailer/class.smtp.php");
        $db = St_Registry::getDB();
        $select = $db->select()
                ->from(array('u' => 'email_setting'))
                ->where("id  = 1");
        $arrayRow = $db->fetchRow($select);
        $data = json_decode($arrayRow['smtp_options'], true);

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->Host = $data['smtpHost']; // SMTP server
        $mail->SMTPDebug = 0;                     // enables SMTP debug information (for testing)
        $mail->Port = $data['smtpPort'];                    // set the SMTP port for the GMAIL server
        if ($data['smtpAuthentication'] == 1) {
            $mail->SMTPAuth = true;                  // enable SMTP authentication
            $mail->Username = $data['smtpUsername']; // SMTP account username
            $mail->Password = $data['smtpPassword'];        // SMTP account password
        }
        if ($data['smtpSsl'] == 'ssl') {
            $mail->SMTPSecure = "ssl";
        }
        if ($data['smtpSsl'] == 'tls') {
            $mail->SMTPSecure = "tls";
        }
        $mail->IsHTML(true);
        $mail->SetFrom($data['smtpUsername'], $_POST['fromname']);
        $mail->AddAddress($_POST['tomail'], $_POST['toname']);
        if ($_POST['subject'] == '') {
            $mail->Subject = "LGD email test"; //$item->subject;//'Sending email scheduling '.date("m/d/Y H:i",$item->date_time);
        } else {
            $mail->Subject = $_POST['subject'];
        }
        $mail->MsgHTML($_POST['message'] . "&nbsp");
        //var_dump($mail);
        if (!$mail->Send()) {
            echo "SMTP Error: Could not connect to SMTP host.";
            //echo "<br>Mailer Error: " . $mail->ErrorInfo."<br>";
        } else {
            echo 'Sending mail successfully';
        }
        die();
    }

    public function communicationAction() {

        $canAdd = true;
        $result = false;

        $this->view->baselink = St_Registry::getConfig("base_url");
        $typeObj = St_Registry::getDB();

        $datas = $typeObj->query("SELECT keyword, value  from setting where keyword='default_fromname'");
        $this->view->table_row = $datas->fetchColumn(1);
        $datas = $typeObj->query("SELECT keyword, value  from setting where keyword='default_sendemail'");
        $this->view->session_row = $datas->fetchColumn(1);

        $data = $this->_getParam("data", false);

        if ($data) {

            if ($canAdd) {
                $typeObj = St_Registry::getDB();
                $result = $typeObj->query("update setting set value='" . $data['default_fromname'] . "' where keyword='default_fromname'");
                $result = $typeObj->query("update setting set value='" . $data['default_sendemail'] . "' where keyword='default_sendemail'");
            }

            if ($result) {
                $user = $this->_getCurrentUser();
                $this->logger->log($user['UserName'] . " edits the default email Setting");
                $this->view->msg = "Update email setting successfully";
            } else {
                $this->view->msg = "Can't update email setting";
            }
            $this->view->data = $data;
            $this->_redirect("{$currentControllerName}/translate/communication");
        }
    }

    public function deleteimageAction() {

        Zend_Loader::loadClass("St_CourseLocation");
        $courseLocationImageObj = new St_CourseLocation(array('name' => 'courselocationimage'));
        $CourseLocationImageID = $this->_getParam("CourseLocationImageID", false);
        if ($CourseLocationImageID && $CourseLocationImageID != 'undefined') {
            $courseLocationImageObj->delete($courseLocationImageObj->getAdapter()->quoteInto("CourseLocationImageID = ?", $CourseLocationImageID));
            //redirect to other action
            if ($_POST['ajax'])
                die;
        }
        die;
    }
    
}

